<template>
    <d2-container>
        <!-- 搜索表头 -->
        <template slot="header">
            <el-form :inline="true" :model="searchForm" ref="searchForm" :rules="searchFormRules" size="small" v-if="showHeader"
                class="searchHeader">

                <el-form-item label="存储类型" prop="storeType">
                    <ec-dict-select v-model="searchForm.storeType" dictType="store_type" placeholder="选择存储类型"
                        defaultIndex="0" clearable>
                    </ec-dict-select>
                </el-form-item>
                <el-form-item label="存储空间" prop="pkFileSpace">
                    <ec-select v-model="searchForm.pkFileSpace" source="fileSpace" placeholder="选择文件空间" clearable>
                    </ec-select>
                </el-form-item>

                <el-form-item label="文件名称" prop="fileName">
                    <el-input v-model="searchForm.fileName" placeholder="请输入文件名称" clearable />
                </el-form-item>
                <el-form-item label="文件类型" prop="fileType">
                    <el-input v-model="searchForm.fileType" placeholder="请输入文件类型" clearable />
                </el-form-item>
                <el-form-item label="文件编号" prop="pkFile">
                    <el-input v-model="searchForm.pkFile" placeholder="请输入文件编号" clearable />
                </el-form-item>

                <el-form-item label="操作">
                    <el-button type="primary" @click="getDataTable">
                        <d2-icon name="search" />
                        查询
                    </el-button>
                    <el-button @click="handleFormReset">
                        <d2-icon name="refresh" />
                        重置
                    </el-button>
                </el-form-item>

            </el-form>
        </template>

        <!-- 表格表头 -->
        <div class="table-header">
            <div>
                <!-- <el-button type="primary" icon="el-icon-circle-plus-outline" size="small" @click="addOrUpdate()">添加</el-button> -->
                <el-button type="primary" icon="el-icon-upload2" size="small" @click="showUpload()">上传文件</el-button>
                <el-button type="primary" icon="el-icon-download" size="small" @click="batchDownload()">打包下载</el-button>
                <el-button type="primary" icon="el-icon-upload2" size="small" @click="uploadInit()">上传（组件）</el-button>
            </div>
            <div>
                <ec-prompt-button content="刷新" icon="el-icon-refresh" @click="getDataTable()"></ec-prompt-button>
                <ec-prompt-button content="搜索" icon="el-icon-search" @click="changeHeader()"></ec-prompt-button>
                <ec-prompt-button content="导入" icon="el-icon-download"></ec-prompt-button>
                <ec-prompt-button content="导出" icon="el-icon-upload2"></ec-prompt-button>
                <ec-prompt-button content="复制" icon="el-icon-document-copy" @click="copyHandler()"></ec-prompt-button>
                <ec-prompt-button content="分享" icon="el-icon-share" @click="shareHandler()"></ec-prompt-button>
            </div>
        </div>


        <!-- 表格表体 -->
        <ec-table :data="tabledata" @selection-change="handleSelectionChange" v-loading="loading">
            <el-table-column type="selection" header-align="center" align="center" width="50">
            </el-table-column>
            <el-table-column prop="pkFile" header-align="center" align="center" show-overflow-tooltip width="50"
                label="编号">
            </el-table-column>
            <el-table-column label="图标" header-align="center" align="center" width="100">
                <template slot-scope="scope">
                    　　　　<ec-file-img v-model="scope.row.fileName" style="height:40px"></ec-file-img>
                    　　</template>
            </el-table-column>
            <el-table-column prop="fileSpaceDesc" header-align="center" align="center" show-overflow-tooltip width="200"
                label="文件空间">
            </el-table-column>
            <el-table-column prop="fileName" header-align="center" align="center" show-overflow-tooltip min-width="200"
                label="文件名">
            </el-table-column>
            <el-table-column prop="fileType" header-align="center" align="center" show-overflow-tooltip width="100"
                label="文件类型">
            </el-table-column>
            <el-table-column prop="storeTypeDesc" header-align="center" align="center" show-overflow-tooltip width="100"
                label="存储类型">
            </el-table-column>
            <el-table-column prop="fileSize" header-align="center" align="center" show-overflow-tooltip width="100"
                label="文件大小">
            </el-table-column>
            <el-table-column prop="filePath" header-align="center" align="center" show-overflow-tooltip width="200"
                label="文件路径">
            </el-table-column>
            <!-- <el-table-column prop="isDeleteDesc" header-align="center" align="center" show-overflow-tooltip width="200"
                label="删除标识">
            </el-table-column> -->
            <el-table-column prop="createdByName" header-align="center" align="center" show-overflow-tooltip width="160"
                label="文件所属人">
            </el-table-column>
            <el-table-column prop="createdTime" header-align="center" align="center" show-overflow-tooltip width="200"
                label="创建日期">
            </el-table-column>
            <el-table-column fixed="right" header-align="center" align="center" width="180" label="操作">
                <template slot-scope="scope">
                    <el-button type="text" size="small" @click="copyInfo(scope.row)">复制信息
                    </el-button>
                    <el-button type="text" size="small" @click="download(scope.row)">下载
                    </el-button>
                    <el-button type="text" size="small" @click="deleteHandle(scope.row.pkFile)">删除</el-button>
                </template>
            </el-table-column>

        </ec-table>

        <!-- 表格表尾 -->
        <template slot="footer">
            <!-- <el-button type="primary" size="mini" :loading="uploading" style="float:left;">
                <d2-icon name="cloud-upload" />
                Upload log data
            </el-button> -->

            <ec-pagination :page="page" @size-change="handleSizeChange" @current-change="handleCurrentChange">
            </ec-pagination>
        </template>
        <!-- 弹窗, 新增 / 修改 -->
        <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataTable"></add-or-update>

        <upload-dailog v-if="uploadDialogVisible" ref="uploadDailog" @refreshDataList="getDataTable"></upload-dailog>

        <!-- 文件上传 -->
        <ec-upload v-if="uploadVisible" ref="upload" @callback="filecallback"></ec-upload>
    </d2-container>
</template>

<script>
    import * as filemanagerService from '@/api/file/filemanager'
    import * as fileService from '@/api/file/file'
    import AddOrUpdate from './add-or-update'
    import UploadDailog from './upload-dailog'


    export default {
        name: "file-manager",
        data() {
            return {
                searchForm: {
                    fileName: '',
                    fileType: '',
                    storeType: '',
                    pkFile: '',
                    pkFileSpace: ''
                },
                searchFormRules: {
                    storeType: [{
                        required: true,
                        message: '必填项',
                        trigger: 'change'
                    }]
                },
                page: {
                    page: 1,
                    limit: 10,
                    total: 0
                },
                showHeader: true,
                tabledata: [],
                multipleSelection: [],
                loading: false,
                addOrUpdateVisible: false,
                uploadDialogVisible: false,
                uploadVisible: true
            }
        },
        components: {
            AddOrUpdate,
            UploadDailog
        },
        mounted() {
            this.getDataTable()
        },
        methods: {
            // 文件上传
            uploadInit() {
                this.uploadVisible = true
                this.$nextTick(() => {
                    this.$refs.upload.init()
                })
            },
            // 获取数据列表
            getDataTable() {
                this.$refs['searchForm'].validate((valid) => {
                    if (valid) {
                        this.loading = true
                        let query = {
                            page: this.page.page,
                            limit: this.page.limit,
                            fileName: this.searchForm.fileName,
                            fileType: this.searchForm.fileType,
                            storeType: this.searchForm.storeType,
                            pkFile: this.searchForm.pkFile,
                            pkFileSpace: this.searchForm.pkFileSpace
                        };
                        filemanagerService.getfilemanagerlist(query).then(data => {
                            this.tabledata = data.list;
                            this.page.total = data.totalCount;
                            this.loading = false;
                        }).catch((res) => {
                            this.loading = false;
                        });
                    }
                })

            },
            //切换页数
            handleSizeChange(val) {
                this.page.limit = val;
                this.getDataTable();
            },
            // 翻页
            handleCurrentChange(val) {
                this.page.page = val;
                this.getDataTable();
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 切换显示搜索表头
            changeHeader() {
                this.showHeader = !this.showHeader
            },
            // 重置搜索表单
            handleFormReset() {
                this.$refs.searchForm.resetFields()
            },
            // 新增 / 修改
            addOrUpdate(id) {
                this.addOrUpdateVisible = true
                this.$nextTick(() => {
                    this.$refs.addOrUpdate.init(id)
                })
            },
            // 复制
            copyInfo(file) {
                var input = document.createElement("textarea"); // 直接构建input
                let text = "文件名称：[" + file.fileName + "]\r\n文件地址：[" + file.fileUrl + "]";
                input.value = text; // 设置内容
                document.body.appendChild(input); // 添加临时实例
                input.select(); // 选择实例内容
                document.execCommand("Copy"); // 执行复制
                document.body.removeChild(input); // 删除临时实例

                document.execCommand("Copy"); // 执行浏览器复制命令
                this.$message({
                    message: '复制成功',
                    type: 'success'
                });
            },
            copyHandler(){
                
            },
            shareHandler() {
                if (this.multipleSelection.length > 0) {

                    let copyInfos = this.multipleSelection;
                    var input = document.createElement("textarea"); // 直接构建input
                    copyInfos.forEach((item, index) => {
                        let text = "文件名称：[" + item.fileName + "]\r\n文件地址：[" + item.fileUrl + "]\r\n";
                        input.value = input.value + text; // 设置内容
                    })
                    document.body.appendChild(input); // 添加临时实例
                    input.select(); // 选择实例内容
                    document.execCommand("Copy"); // 执行复制
                    document.body.removeChild(input); // 删除临时实例

                    document.execCommand("Copy"); // 执行浏览器复制命令
                    this.$message({
                        message: '复制成功',
                        type: 'success'
                    });
                } else {
                    this.$message.warning("请至少选择一项！")
                }
            },
            // 下载文件方法
            download(file) {
                // console.log(file)
                if (file) {
                    let params = "";
                    params = params + "fileIds=" + file.pkFile + "&"
                    params = params + "zip="
                    fileService.download(params).then(data => {
                        this.downloadFile(data, file.fileName, file.mimeType)
                    })
                } else {
                    this.$message.error("文件参数错误！")
                }
            },
            // 打包下载
            batchDownload() {
                var fileIds = this.multipleSelection.map(item => {
                    return item.pkFile
                })

                if (fileIds.length > 0) {
                    let params = "";

                    fileIds.forEach(item => {
                        params = params + "fileIds=" + item + "&"
                    })
                    params = params + "zip=1"
                    fileService.download(params).then(data => {
                        this.downloadFile(data, 'file.zip', 'application/zip')

                    })
                } else {
                    this.$message.warning("请选择要打包下载的文件。")
                }
            },
            // 下载文件
            downloadFile(data, fileName, fileType = 'application/octet-stream') {
                if (!data) {
                    return
                }
                let url = window.URL.createObjectURL(new Blob([data], {
                    type: fileType
                }))
                let link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.setAttribute('download', fileName)
                document.body.appendChild(link)
                link.click()
            },
            showUpload() {
                this.uploadDialogVisible = true;
                this.$nextTick(() => {
                    this.$refs.uploadDailog.init()
                })
            },
            // 删除
            deleteHandle(id) {
                if (id) {
                    this.$confirm("确认删除？", "确认信息", {
                        distinguishCancelAndClose: true,
                        confirmButtonText: "删除",
                        cancelButtonText: "取消"
                    }).then(() => {
                        filemanagerService.delfilemanager(id).then(() => {
                            this.getDataTable();
                        });
                    });
                }
            },
            // 文件上传回掉函数
            filecallback(fileList) {
                this.getDataTable()
                // console.log(fileList)
            }
        }
    }
</script>